﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
using System.Xml.Linq;

namespace ApiDoc
{
    /// <summary>
    /// Extension methods for simplifying the use of ApiDocumentationManager usig the System.IO namespace to load files.
    /// </summary>
    public static class ApiDocumentationManagerExtensions_IO
    {
        /// <summary>
        /// Load the assemblies from <paramref name="fileName"/>.
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="fileName"></param>
        public static void LoadAssembly(this ApiDocumentationManager manager, string fileName)
        {
            var assembly = Assembly.LoadFrom(fileName);
            manager.AddAssembly(assembly);
        }

        /// <summary>
        /// Load all assemblies from <paramref name="path"/>.
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="path"></param>
        public static void LoadAssemblies(this ApiDocumentationManager manager, string path)
        {
            var assemblies = Directory.GetFiles(path)
                .Where(item =>
                    Path.GetExtension(item).ToLowerInvariant() == ".dll"
                    || Path.GetExtension(item).ToLowerInvariant() == ".exe"
                    )
                .ToList();
            foreach (string fileName in assemblies) {
                var assembly = Assembly.LoadFrom(fileName);
                manager.AddAssembly(assembly);
            }
        }

        /// <summary>
        /// Load the XML from <paramref name="fileName"/>.
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="fileName"></param>
        public static void LoadXml(this ApiDocumentationManager manager, string fileName)
        {
            var xml = XDocument.Load(fileName);
            manager.AddXml(xml);
        }

        /// <summary>
        /// Load all XML from <paramref name="path"/>.
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="path"></param>
        public static void LoadXmls(this ApiDocumentationManager manager, string path)
        {
            var files = Directory.GetFiles(path)
                .Where(item => Path.GetExtension(item).ToLowerInvariant() == ".xml")
                .ToList();
            foreach (string fileName in files) {
                var xml = XDocument.Load(fileName);
                manager.AddXml(xml);
            }
        }
    }
}
